/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mapbox.ohos.gestures;

import ohos.agp.components.VelocityDetector;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

import java.util.Set;

/**
 * Base class for all progressive gesture detectors.
 *
 * @param <L> listener that will be called with gesture events/updates.
 */
public abstract class ProgressiveGesture<L> extends MultiFingerGesture<L> {

    private final Set<Integer> handledTypes = provideHandledTypes();

    private boolean isInProgress;
    private boolean interrupted;

    VelocityDetector velocityDetector;
    float velocityX;
    float velocityY;

    public ProgressiveGesture(Context context, OhosGesturesManager gesturesManager) {
        super(context, gesturesManager);
    }

    /**
     * provideHandledTypes
     * @return Set
     */
    protected abstract Set<Integer> provideHandledTypes();

    @Override
    protected boolean analyzeEvent(TouchEvent motionEvent) {
        int action = motionEvent.getAction();
        if (action == TouchEvent.PRIMARY_POINT_DOWN || action == TouchEvent.OTHER_POINT_DOWN
            || action == TouchEvent.PRIMARY_POINT_UP
            || action == TouchEvent.CANCEL) {
            // configuration changed, reset data
            reset();
        }

        if (interrupted) {
            interrupted = false;
            reset();
            gestureStopped();
        }

        if (velocityDetector != null) {
            velocityDetector.addEvent(getCurrentEvent());
        }

        boolean movementHandled = super.analyzeEvent(motionEvent);

        if (action == TouchEvent.PRIMARY_POINT_UP || action == TouchEvent.OTHER_POINT_UP) {
            if (pointerIdList.size() < getRequiredPointersCount() && isInProgress) {
                gestureStopped();
                return true;
            }
        } else if (action == TouchEvent.CANCEL) {
            if (isInProgress) {
                gestureStopped();
                return true;
            }
        }

        return movementHandled;
    }

    /**
     * gestureStarted
     */
    protected void gestureStarted() {
        isInProgress = true;
        if (velocityDetector == null) {
            velocityDetector = VelocityDetector.obtainInstance();
        }
    }

    /**
     * gestureStopped
     */
    protected void gestureStopped() {
        isInProgress = false;
        if (velocityDetector != null) {
            velocityDetector.calculateCurrentVelocity(1000);
            velocityX = velocityDetector.getHorizontalVelocity();
            velocityY = velocityDetector.getVerticalVelocity();
            velocityDetector.clear();
            velocityDetector = null;
        }
        reset();
    }

    Set<Integer> getHandledTypes() {
        return handledTypes;
    }

    /**
     * Check whether a gesture has started and is in progress.
     *
     * @return true if gesture is in progress, false otherwise.
     */
    public boolean isInProgress() {
        return isInProgress;
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (!enabled) {
            interrupt();
        }
    }

    /**
     * Interrupt a gesture by stopping it's execution immediately.
     * Forces gesture detector to meet start conditions again in order to resume.
     */
    public void interrupt() {
        if (isInProgress()) {
            this.interrupted = true;
        }
    }
}
